// useIndex.ts
import { ref } from "vue";
import { useMapViewer } from "@/composables/useMapViewer";
import * as Cesium from "cesium"
import dayjs from "dayjs";
import { RedSat_LLA_Position, BlueSat_LLA_Position, drawRelativePath } from './data'

/**
 * 地图查看器逻辑封装
 * @returns {Object} 包含以下内容：
 *   - viewerContainer: 地图容器DOM引用
 *   - initViewer: 初始化地图方法
 *   - destroyViewer: 销毁地图方法
 */
export const useIndex = () => {
  // 创建对模板中 viewerContainer 的响应式引用
  const viewerContainer = ref<HTMLElement | null>(null);

  /**
   * 从地图功能模块解构方法
   * @see useMapViewer 实现地图核心逻辑
   */
  const { initViewer, destroyViewer, cesiumViewer } = useMapViewer();



  /**
   * 在下方编写测试逻辑
   */
  // .......
  let startT = parseTime(dayjs('9 Aug 2025 09:29:00.000').format('YYYY-MM-DDTHH:mm:ss'))
  let stopT = parseTime(dayjs('9 Aug 2025 16:30:00.000').format('YYYY-MM-DDTHH:mm:ss'))

  const initScene = () => {
    if (!cesiumViewer.value) return;
    const viewer = cesiumViewer.value.viewer!
    // let targetPositions = dataPross(targetPositionList)
    // let mainPositions = dataPross(mainPositionList)
    let mainPositions = dataPross(BlueSat_LLA_Position)
    let targetPositions = dataPross(RedSat_LLA_Position)
    viewer.shadowMap.enabled = false;

    // 禁用HDR（避免自动亮度调节）
    viewer.scene.highDynamicRange = false;
    viewer.scene.light = new Cesium.DirectionalLight({
      intensity: 1.0,
      direction: new Cesium.Cartesian3(-1, 1, -1) // 方向指向地心
    });

    console.log('targetPositions', targetPositions)
    console.log('mainPositions', mainPositions)
    cesiumViewer.value.viewer!.clock.startTime = startT
    cesiumViewer.value.viewer!.clock.stopTime = stopT
    cesiumViewer.value.viewer!.clock.currentTime = startT
    cesiumViewer.value.viewer!.clock.clockRange = Cesium.ClockRange.LOOP_STOP
    cesiumViewer.value.viewer!.clock.multiplier = 1
    cesiumViewer.value.viewer!.timeline.zoomTo(startT, stopT)
    // 添加目标卫星
    // let main = addSatellite(mainPositions, true, Cesium.Color.YELLOW)
    // let target = addSatellite(targetPositions, false)
    // drawRelativePath(cesiumViewer.value.viewer, startT, stopT, target, main, 'main', 'target', Cesium.Color.BLUE)
    // // 添加目标卫星
    let main = addSatellite(mainPositions, true, Cesium.Color.YELLOW)
    let target = addSatellite(targetPositions, false)


    cesiumViewer.value.viewer!.trackedEntity = main
    viewer.flyTo([main, target])
    drawRelativePath(cesiumViewer.value.viewer, startT, stopT, target, main, 'main', 'target', Cesium.Color.BLUE)
    const laserSpeed = 299792.458; // 单位：米/秒
    // 创建激光线（初始长度为0）
    let laserLine = cesiumViewer.value.viewer!.entities.add({
      name: 'Laser',
      polyline: {
        positions: new Cesium.CallbackProperty(function (time, result) {

          const positionB = main.position!.getValue(time);
          const positionA = target.position!.getValue(time);
          if (!positionA || !positionB) return [];
          // 计算两点距离
          const distance = Cesium.Cartesian3.distance(positionA, positionB);
          const travelTime = distance / laserSpeed; // 激光飞行时间
          const elapsed = Cesium.JulianDate.secondsDifference(time as Cesium.JulianDate, startT);
          if (elapsed < 0) {
            return [positionA, positionA];
          }
          const progress = Math.min(elapsed / travelTime, 1.0);
          if (progress >= 1.0) {
            // 激光到达目标，保持完整长度
            return [positionA, positionB];
          }

          // 计算当前终点位置
          const currentEnd = Cesium.Cartesian3.lerp(
            positionA,
            positionB,
            progress,
            new Cesium.Cartesian3()
          );

          return [positionA, currentEnd];
        }, false),
        width: 20,
        material: new Cesium.PolylineGlowMaterialProperty({
          glowPower: 0.2,
          color: Cesium.Color.CYAN
        })
      }
    });

  }
  function addSatellite(mainPositions: any[], isPath = false, color = Cesium.Color.WHITE) {
    let targetPath = computedPosition(mainPositions)
    let entity = cesiumViewer.value!.viewer!.entities.add({
      //关联时间轴  TimeIntervalCollection管理时间间隔数据的集合  把时间轴的起止时间同步为实体的
      availability: new Cesium.TimeIntervalCollection([
        new Cesium.TimeInterval({
          start: startT,
          stop: stopT
        })
      ]),
      position: targetPath,
      orientation: new Cesium.VelocityOrientationProperty(targetPath),
      path: {
        show: isPath,
        resolution: 60,
        width: 1,
        material: color || Cesium.Color.YELLOW
      },
      point: {
        pixelSize: 24,
        color: color || Cesium.Color.YELLOW.withAlpha(0.5),
        outlineColor: color || Cesium.Color.YELLOW.withAlpha(0.8),
        outlineWidth: 1
      },
      model: {
        uri: "/SampleData/models/CesiumDrone/CesiumDrone.glb",
        minimumPixelSize: 128,

      }
      // cylinder: {
      //   HeightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
      //   length: 700000,
      //   topRadius: 0,
      //   bottomRadius: 700000 / 2,
      //   material: Cesium.Color.RED.withAlpha(0.4),
      //   outline: true,
      //   numberOfVerticalLines: 0,
      //   outlineColor: Cesium.Color.RED.withAlpha(0.8),
      // },
    })
    return entity
  }
  return {
    viewerContainer, // 暴露给模板使用的容器引用
    initViewer, // 暴露初始化方法
    destroyViewer, // 暴露清理方法
    initScene

  };
};

function parseTime(time: string) {
  return Cesium.JulianDate.fromIso8601(time)
}

function dataPross(ps: any) {
  let mainPositions = ps.map((t: any) => {
    let arr = t.dataTime.split(/\s+/)
    return {
      x: arr[4],
      y: arr[5],
      z: arr[6],
      dateTime: arr[0] + ' ' + arr[1] + ' ' + arr[2] + ' ' + arr[3]
    }
  })

  return mainPositions
}
function computedPosition(positions: any[]) {
  let property = new Cesium.SampledPositionProperty(Cesium.ReferenceFrame.INERTIAL)
  for (let i = 0; i < positions.length; i++) {
    let time = parseTime(dayjs(positions[i].dateTime).format('YYYY-MM-DDTHH:mm:ssZ'))
    // console.log(
    //   "addSample",
    //   dayjs(positions[i].dateTime).format("YYYY-MM-DDTHH:mm:ss"),
    //   positions[i].x
    // );
    // console.log("startT", time);
    let position = new Cesium.Cartesian3(
      Number(positions[i].x) * 1000,
      Number(positions[i].y) * 1000,
      Number(positions[i].z) * 1000
    )
    property.addSample(time, position)
  }

  return property
}